package com.yy.finvideoplayer.danmu

import android.content.Context
import android.graphics.Color
import android.graphics.SurfaceTexture
import android.graphics.Typeface
import android.icu.text.Transliterator.Position
import android.util.AttributeSet
import android.util.Log
import android.util.TypedValue
import android.view.Surface
import android.view.TextureView
import android.widget.TextView
import com.yy.finvideoplayer.IVideoPlayer
import com.yy.finvideoplayer.PlayListener
import com.yy.finvideoplayer.R
import com.yy.finvideoplayer.danmu.control.Controller
import com.yy.finvideoplayer.danmu.control.SurfaceProxy
import com.yy.finvideoplayer.model.PlayerOptions
import com.yy.finvideoplayer.videoview.VideoPlayer
import java.util.LinkedList

/**
 * @Description: DMTextureView
 * @Author: yiw89
 * @CreateDate: 2025/9/15 15:54
 * @Version: 1.0
 */
class DMTextureView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : TextureView(context, attrs, defStyleAttr), TextureView.SurfaceTextureListener, DM,
    PlayListener {

    private var mSurface: Surface? = null
    private var mController: Controller? = null
    private val builder: Controller.Builder
    private var options: PlayerOptions? = null

    private var mIsSameLayer = false
    val emitter = DanmuEmitter()
    private var lastDanmuPosition = 0
    val myDanmuList = LinkedList<PlayerOptions.DanmakuItem>()

    init {
        surfaceTextureListener = this
        isOpaque = false

        val a = context.obtainStyledAttributes(attrs, R.styleable.DMTextureView, defStyleAttr, 0)

        val direction = Direction.getType(
            a.getInt(
                R.styleable.DMTextureView_dm_direction,
                Direction.RIGHT_LEFT.value
            )
        )
        val span = a.getDimensionPixelOffset(
            R.styleable.DMTextureView_dm_span,
            Util.dp2px(context, 2F)
        )
        val sleep = a.getInt(R.styleable.DMTextureView_dm_sleep, 0)
        val spanTime = a.getInt(R.styleable.DMTextureView_dm_span_time, 0)
        val vSpace = a.getDimensionPixelOffset(
            R.styleable.DMTextureView_dm_v_space,
            Util.dp2px(context, 10F)
        )
        val hSpace = a.getDimensionPixelOffset(
            R.styleable.DMTextureView_dm_h_space,
            Util.dp2px(context, 10F)
        )

        builder = Controller.Builder()
            .setDirection(direction)
            .setSpan(span)
            .setSleep(sleep)
            .setSpanTime(spanTime)
            .sethSpace(hSpace)
            .setvSpace(vSpace)
        a.recycle()
    }

    override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
        mSurface = Surface(surface)
        mController = builder.setSurfaceProxy(SurfaceProxy(mSurface!!))
            .setWidth(width)
            .setHeight(height)
            .build()
        if (!mIsSameLayer) {
            mController?.start()
        }
    }

    fun initController(surface: Surface) {
        if (mSurface != surface) {
            mController = builder.setSurfaceProxy(SurfaceProxy(mSurface!!))
                .setWidth(width)
                .setHeight(height)
                .build()
            mSurface = surface
        }
    }

    fun setIsSameLayer(sameLayer: Boolean) {
        mIsSameLayer = sameLayer
    }

    fun setOptions(options: PlayerOptions) {
        this.options = options
    }

    override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {
        mController?.setSize(width, height)
    }

    override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
        mSurface?.release()
        mSurface = null
        mController?.destroy()
        return true
    }

    override fun onWindowFocusChanged(hasWindowFocus: Boolean) {
        super.onWindowFocusChanged(hasWindowFocus)
        if (mSurface == null) return
        /*if (hasWindowFocus) {
            mController?.resume()
        } else {
            mController?.pause()
        }*/
    }

    override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {
        // 空实现
    }

    override fun getController(): Controller? {
        return mController
    }

    override fun onStatusAndMode(status: Int, mode: Int) {
        // 空实现
    }

    override fun onEvent(what: Int, vararg extra: Int?) {

        when (what) {
            IVideoPlayer.EVENT_PREPARE_START -> {
                if (options?.danmuList?.isNotEmpty() == true) {
                    emitter.reload(options!!.danmuList)
                }
            }
            IVideoPlayer.EVENT_PREPARE_END -> {
                //如果默认显示弹幕，在这里开始准备
                if(options?.enableDanmu == true){
                    (parent as VideoPlayer).setDanmuEnable(true)
                }
            }
            IVideoPlayer.EVENT_PLAY -> {
                emitter.resume()
                mController?.resume()
            }
            IVideoPlayer.EVENT_PAUSE -> {
                emitter.pause()
                mController?.pause()
            }
            IVideoPlayer.EVENT_ERROR -> {
                mController?.clean()
            }
            IVideoPlayer.EVENT_COMPLETION -> {
                mController?.pause()
            }
            IVideoPlayer.EVENT_RELEASE -> {
                mController?.clean()
            }
            IVideoPlayer.EVENT_BUFFERING_START -> {
                mController?.pause()
            }
            IVideoPlayer.EVENT_SEEK_TO -> {
                // 空实现

            }
            IVideoPlayer.EVENT_SEEK_COMPLETION, IVideoPlayer.EVENT_BUFFERING_END -> {


            }
        }
    }

    fun handlePrintDanmu(position: Int) {
        if (lastDanmuPosition == 0) {
            lastDanmuPosition = position
            return
        }

        emitter.emit(lastDanmuPosition, position) { dms ->
            dms.forEach {
                printDanmu(it.text, it.colorValue)
            }
            if (myDanmuList.isNotEmpty()) {
                while (myDanmuList.isNotEmpty()) {
                    val it = myDanmuList.removeAt(0)
                    printDanmu(it.text, it.colorValue)
                    emitter.insertDanmakuItem(it)
                }
            }
        }
        lastDanmuPosition = position
    }

    private fun printDanmu(text: String, color: Int = Color.WHITE) {
        controller?: return
        controller!!.setDirection(Direction.RIGHT_LEFT)
        controller!!.add {
            TextView(context).apply {
                setTextColor(color)
                setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20F)
                typeface = Typeface.DEFAULT_BOLD

                this.text = text
            }
        }
    }




}